package ua.races.command.implementation;

import ua.races.command.ServletCommand;
import ua.races.dao.RacesDaoImpl;
import org.apache.log4j.Logger;
import ua.races.command.ServletCommand;
import ua.races.dao.RacesDaoImpl;
import ua.races.vo.Horse;
import ua.races.vo.Race;
import ua.races.vo.Bet;
import ua.races.vo.Client;
import ua.races.vo.Horse;
import ua.races.vo.Race;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

public class ViewHorsesFromRaceCommand implements ServletCommand {

    private static final Logger log = Logger.getLogger(ViewHorsesFromRaceCommand.class.getName());

    public void execute(HttpServletRequest req, HttpServletResponse resp, ServletContext context) {

        final long raceId = Long.parseLong(req.getParameter("raceId"));
        Race race = new Race();
        race.setRaceId(raceId);
        final List<Horse> horses;
        final HttpSession session;
        log.info("create parameters for view horses from race");

        try {
            RacesDaoImpl dao = (RacesDaoImpl) context.getAttribute("DAO");

            horses = dao.getHorsesInRace(race);

            if (horses != null) {
                // todo isRequestedSessionIdValid - ?
                // if ((true) || (!req.isRequestedSessionIdValid())) {
                session = req.getSession(true);
                req.setAttribute("horses",horses);
//              session.setAttribute("horses", horses);
//                List<Bet> bets = dao.findAllClientBets(client);
//                session.setAttribute("bets",bets);
                // todo List<Race> races = dao.findAllRacesForBet();
                List<Race> races = dao.findAllRaces();
                session.setAttribute("races",races);
                // }
                log.info("All horses for certain race have been found");
                context.getRequestDispatcher("/client.jsp").forward(req, resp);
            } else {
                req.setAttribute("horses", null);
                log.info("Zero horses found!!!");
                context.getRequestDispatcher("/client.jsp").forward(req, resp);
            }

        } catch (SQLException e) {
            log.error(e);
        } catch (ServletException e) {
            log.error(e);
        } catch (IOException e) {
            log.error(e);
        }


    }
}
